package sim.core.utils;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * properties 文件读取到Map
 * 
 * @author Feny
 * @email 1220301855@qq.com
 * @version 1.0
 * @date 2018年7月26日下午2:58:35
 */
public class PropUtils {
	private static Map<String, String> propMap = new LinkedHashMap<>();

	/**
	 * 加载properties文件，文件名不包含.properties后缀<br>
	 * 示例：<br>
	 * 1、加载src下application.properties：<br>
	 * PropUtils.load("application");<br>
	 * 2、加载com/test/application.properties<br>
	 * PropUtils.load("com/test/application")
	 * 
	 * @author Feny
	 * @date 2018年7月27日上午10:55:51
	 * @param propName
	 */
	public static void load(String propName) {
		try {
			ResourceBundle bundle = ResourceBundle.getBundle(propName);
			Enumeration<String> keys = bundle.getKeys();
			while (keys.hasMoreElements()) {
				String name = keys.nextElement();
				setProp(name, bundle.getString(name).trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getProp(String name) {
		return propMap.get(name);
	}

	private static void setProp(String name, String value) {
		if (propMap.containsKey(name)) {
			throw new RuntimeException("properties文件中，存在重复的key：" + name);
		}
		propMap.put(name, value);
	}

	public static void main(String[] args) {
		PropUtils.load("application");
		System.out.println(PropUtils.getProp("servlet.request.suffix"));
	}
}
